#!/bin/bash
readonly source_driver="drivers/nvme/host"
readonly source_root="/root/projects/openeuler"
readonly source_dir="${source_root}/${source_driver}"

readonly driver_base="arkins"
readonly driver_name="nvme-host"
readonly driver_root="/lib/modules/$(uname -r)"
readonly driver_build="${driver_root}/build"
readonly driver_dir="${driver_root}/${driver_base}/${driver_name}"
readonly depmod_file="/etc/depmod.d/${driver_base}-${driver_name}.conf"


function install_file()
{
    echo "install ${1} => ${2}"
    install -m 550 "${1}" "${2}"
}

function build_clean()
{
    echo "===================compile========================"
    echo "source_dir=${source_dir}"
    make -C ${driver_build} M=${source_dir} clean
    ls -l ${source_dir} | grep ko
}

function build_modules()
{
    local compile_cflags="-I${source_root}/test"

    echo "===================compile========================"
    echo "${source_dir}"
    make -C ${driver_build} M=${source_dir} EXTRA_CFLAGS=${compile_cflags} modules
    echo "===================files========================"
    echo "${source_dir}"
    ls ${source_dir} | grep ko
}

function install_modules()
{
    local module_list=""
    local module_name=""

    echo "===================install========================"
    cd "${source_dir}"
    rm -rf "${driver_dir}"
    mkdir -p "${driver_dir}"

    module_list=$(ls ${source_dir} | grep ko)
    for module_name in ${module_list}
    do
        install_file "${module_name}" "${driver_dir}"
    done

    echo "===================files========================="
    echo "${driver_dir}"
    ls "${driver_dir}"
}

function install_config()
{
    local module_list=""
    local module_name=""

    echo "===================depmod========================"
    echo "${depmod_file}"

    if [ -f "${depmod_file}" ]; then
        return 0
    fi

    touch "${depmod_file}"

    echo "external $(uname -r)  ${driver_dir}" > ${depmod_file}
    
    module_list=$(ls ${source_dir} | grep ko | awk -F "." '{print $1}')
    for module_name in ${module_list}
    do
        echo "override ${module_name} $(uname -r) ${driver_base}/${driver_name}" >> ${depmod_file}
    done

    cat ${depmod_file}
    depmod -a
}

# build_clean
build_modules
install_modules
install_config
